<template>
    <div class="container-page">
        <template v-if="!props.parentId">
            <div class="form__container">
                <n-form ref="formRef" :model="form" :rules="rules" label-placement="left" label-align="right"
                    label-width="120" require-mark-placement="right-hanging">
                    <n-grid :cols="24" :x-gap="24">
                        <n-form-item-gi :span="12" :label="$t('tableColumnLabel.parentTag')" path="tag">
                            <n-input v-model:value="form.tag" placeholder="请输入父节点tag" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" :label="$t('tableColumnLabel.parentLabel')" path="label">
                            <n-input v-model:value="form.label" placeholder="请输入父节点标签">
                            </n-input>
                        </n-form-item-gi>
                    </n-grid>
                    <n-grid :cols="24" :x-gap="24">
                        <n-form-item-gi :span="12" :label="$t('tableColumnLabel.parentValue')" path="value">
                            <n-input v-model:value="form.value" placeholder="请输入父节点值" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" :label="$t('tableColumnLabel.parentRemark')" path="remark">
                            <n-input v-model:value="form.remark" placeholder="请输入父节点备注">
                            </n-input>
                        </n-form-item-gi>
                    </n-grid>
                </n-form>
            </div>
            <div class="footer__button">
                <n-button type="primary" @click="submitForm">{{ $t('button.submit') }}</n-button>
            </div>
        </template>
        <template v-else>
            <div class="form__container">
                <n-table :single-line="false">
                    <thead class="stock_table--header">
                        <tr>
                            <th align="center" width="20%">{{ $t('tableColumnLabel.childLabel') }}</th>
                            <th align="center" width="20%">{{ $t('tableColumnLabel.childValue') }}</th>
                            <th align="center" width="20%">{{ $t('tableColumnLabel.childTag') }}</th>
                            <th align="center" width="20%">{{ $t('tableColumnLabel.childRemark') }}</th>
                            <th align="center" width="20%">{{ $t('tableColumnLabel.operation') }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="loading" v-for="_ in 5">
                            <td align="center">
                                <n-skeleton :width="86" :height="16" :sharp="false" size="medium" />
                            </td>
                            <td align="center">
                                <n-skeleton :width="86" :height="16" :sharp="false" size="medium" />
                            </td>
                            <td align="center">
                                <n-skeleton :width="86" :height="16" :sharp="false" size="medium" />
                            </td>
                            <td align="center">
                                <n-skeleton :width="86" :height="16" :sharp="false" size="medium" />
                            </td>
                            <td align="center">
                                <n-skeleton :width="86" :height="16" :sharp="false" size="medium" />
                            </td>
                        </tr>
                        <tr v-else v-for="(item, index) in childNode" :key="index">
                            <td align="center">
                                {{ item.label }}
                            </td>
                            <td align="center">
                                {{ item.value }}
                            </td>
                            <td align="center">
                                {{ item.tag }}
                            </td>
                            <td align="center">
                                {{ item.remark }}
                            </td>
                            <td align="center">
                                <div class="btn--list">
                                    <!-- <n-button type="primary" @click="submitForm">更新</n-button> -->
                                    <n-button type="error" @click="deleteItem(item.id!)">{{ $t('button.delete') }}</n-button>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td align="center">
                                <n-input v-model:value="form.label" placeholder="请输入子节点标签" />
                            </td>
                            <td align="center">
                                <n-input v-model:value="form.value" placeholder="请输入子节点值" />
                            </td>
                            <td align="center">
                                <n-input v-model:value="form.tag" placeholder="请输入子节点标识" disabled />
                            </td>
                            <td align="center">
                                <n-input v-model:value="form.remark" placeholder="请输入子节点备注" />
                            </td>
                            <td align="center">
                                <div class="btn--list">
                                    <n-button type="primary" @click="submitChildForm" :loading="loading"
                                        :disabled="loading">{{ $t('button.add') }}</n-button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </n-table>
            </div>
        </template>
    </div>
</template>

<script setup lang='ts' name="addPage">
import { addParentNode, addChildNode, getByTag, deleteNode } from '@/api/backend/admin';
import { FormInst, useMessage } from 'naive-ui';

const props = defineProps<{
    parentId: string | null;
    parentTag: string;
}>();
const emit = defineEmits<{
    (e: 'refresh'): void;
}>();
const rules = {
    tag: [
        {
            message: '请填写标记',
            required: true,
            trigger: ['blue', 'input']
        }
    ],
    label: [
        {
            message: '请填写标签/中文名',
            required: true,
            trigger: ['blue', 'input']
        }
    ],
    value: [
        {
            message: '请填写值',
            required: true,
            trigger: ['blue', 'input']
        }
    ],
    remark: [
        {
            message: '请填写备注',
            required: true,
            trigger: ['blue', 'input']
        }
    ]
};
const formRef = ref<null | FormInst>(null);
const loading = ref(true);
const message = useMessage();
const form = reactive<DictVO>({
    tag: '',
    label: '',
    value: '',
    remark: ''
});
const initChildNode = async () => {
    try {
        loading.value = true;
        const res = await getByTag(props.parentTag);
        if (res.code !== 200) throw new Error(res.msg);
        childNode.length = 0; // 清空数组
        res.data.forEach((item: DictVO) => {
            childNode.push(item);
        });
    } catch (error) {
        message.error('获取子节点失败，请稍后重试！');
    } finally {
        loading.value = false;
    }
};
watch(() => props.parentTag, (newVal) => {
    if (newVal) {
        initChildNode();
        form.tag = newVal; // 设置子节点标识为父节点标识
    } else {
        childNode.length = 0; // 清空数组
        form.tag = ''; // 清空子节点标识
    }
});
const childNode = reactive<DictVO[]>([]);
const submitForm = () => {
    formRef.value?.validate((errors) => {
        if (!errors) {
            uploadDate();
        }
        else {
            message.error('请完整输入表单');
        }
    })
};
// 删除节点
const deleteItem = async (id: string) => {
    try {
        const res = await deleteNode(id);
        if (res.code !== 200) throw new Error(res.message);
        initChildNode();
        message.success(res.message);
    } catch (error) {
        message.error(error instanceof Error ? error.message : '错误！');
    }
}
const submitChildForm = () => {
    if (form.tag === '' || form.label === '' || form.value === '') {
        message.error('请完整输入表单');
        return;
    }
    uploadChildDate();
};
const uploadChildDate = async () => {
    try {
        const res = await addChildNode(form, props.parentId as string);
        if (res.code !== 200) throw new Error(res.msg);
        message.success('添加成功！');
        formRef.value?.restoreValidation();
        Object.assign(form, {
            tag: props.parentTag,
            label: '',
            value: '',
            remark: ''
        });
        initChildNode();
    } catch (error) {
        message.error('添加失败，请稍后重试！');
    }
}
const uploadDate = async () => {
    try {
        const res = await addParentNode(form);
        if (res.code !== 200) throw new Error(res.msg);
        message.success('添加成功！');
        emit('refresh');
        formRef.value?.restoreValidation();
        Object.assign(form, {
            tag: '',
            label: '',
            value: '',
            remark: ''
        });
    } catch (error) {
        message.error('添加失败，请稍后重试！');
    }
};
</script>
<style scoped lang='scss'>
.container-page {
    display: grid;
    grid-template-rows: 90% 10%;
    height: calc(100% - 25px);
    overflow: auto;

    .form__container {
        padding: 20px;
    }

    .footer__button {
        height: 100%;
        width: 100%;
        background: rgba(255, 255, 255, 0.2);
        /* 半透明背景 */
        backdrop-filter: blur(10px);
        /* 背景模糊 */
        -webkit-backdrop-filter: blur(10px);
        /* 兼容性前缀 */
        border-top: 1px solid #E7E7E7;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 1rem;
    }
}

.btn--list {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}
</style>